package com.pca.headline.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Method;


public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 响应的MIME类型和乱码问题
        resp.setContentType("application/json;charset=UTF-8");

        String requestURI = req.getRequestURI();
        String[] split = requestURI.split("/");
        String methodName =split[split.length-1];
        // 通过反射获取要执行的方法
        Class clazz = this.getClass();
        Method method = null;
        try {
            method=clazz.getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            // 设置方法可以访问
            method.setAccessible(true);
            // 通过反射执行代码
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Class: " + clazz.getName());
            System.out.println("Method name: " + methodName);
            throw new RuntimeException(e.getMessage());
        }
        //获取全部url
//        String requestURI = req.getRequestURI();
//        String[] uri = requestURI.split("/");
//        String action = uri[uri.length - 1];
//
//        //利用反射通过方法名使用方法
//        Class aClass = this.getClass();
//        try {
//            Method declaredMethod = aClass.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            //暴力破解的访问修饰符的限制
//            declaredMethod.setAccessible(true);
//            //执行方法
//            declaredMethod.invoke(this, req, resp);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
